<template>
	<!-- 人脉圈 个人主页 -->
	<Top-Page class="home-box">
		<NavBar
			title="人脉圈"
			:class="navBar_class"
			left-arrow
			right-more
			@click-left="navBack()"
			@click-right="show = !show"
		/>

		<view class="user-info-box">
			<image
				v-if="query.chat_bg && query.chat_bg != 'null'"
				class="user-bg_img"
				:src="query.chat_bg"
				mode="aspectFill"
			/>
			<image v-else class="user-bg_img" :src="userBg" mode="aspectFill" />
			<view class="user-info-wrap">
				<view class="user-info__name text-one"> {{ query.realname }} </view>
				<user-avator :width="128" :height="128" :src="query.avatar"></user-avator>
			</view>
		</view>

		<!-- 发表过的作品 -->
		<view class="works-list-box" v-if="works_list.length">
			<!-- 年 -->
			<view class="works-item__year" v-for="yearGroup in works_list">
				<view class="year-wrap"> {{ yearGroup.year }} </view>

				<!-- 月 -->
				<view class="works-item__dates" v-for="dateGroup in yearGroup.dates">
					<view class="dates-wrap">
						<view class="day"> {{ dateGroup.date[0] }} </view>
						<view class="month"> {{ dateGroup.date[1] }} </view>
					</view>

					<!-- 日 作品列表 -->
					<view class="works-list">
						<view
							class="works-item"
							v-for="item in dateGroup.items"
							@click.stop="toDetailsMsg(item.trends_id, item.isNew)"
						>
							<view
								v-if="!item.isNew"
								:class="[
									'works-item__thumbnail',
									item.img ? `has-${item.img ? item.img.length : 0}-items` : 'has-1-items',
								]"
							>
								<tetemplate v-for="(it, ind) in item.img">
									<image
										v-if="checkResourceType(it) === 'image'"
										class="works-item__thumbnail-item"
										mode="aspectFill"
										:src="`${it}?imageView2/1/w/200/h/200/q/40`"
									/>
									<image
										v-else
										class="works-item__thumbnail-item"
										mode="aspectFill"
										:src="`${it}?vframe/jpg/offset/1/imageView2/1/w/200/h/200/q/40`"
									/>
								</tetemplate>
								<!-- <image class="works-item__thumbnail-item" mode="aspectFill" v-for="(it, ind) in item.img" :src="it" /> -->
							</view>

							<!-- 相机样式 -->
							<view v-else class="works-item__thumbnail works-item__thumbnail-2" @click="toReleaseDynamic">
								<view class="camera-box">
									<view class="camera-1"></view>
									<view class="camera-2">
										<view class="camera-3"></view>
									</view>
								</view>
							</view>

							<view class="works-item__article">{{ item.content }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="finished-text border-bottom-after" v-if="finished">
			{{ finished_text }}
		</view>

		<!-- 右上角的更多 -->
		<Popup v-model:show="show" position="bottom" closeable round class="more-popup">
			<view class="popup-more-item border-bottom-after" @click.stop="release('camera')">拍摄</view>
			<view class="popup-more-item border-bottom-after" @click.stop="release('album')">从手机相册选择</view>
			<view class="popup-more-item" @click.stop="toVisitor">查看我的访客</view>
		</Popup>
	</Top-Page>
</template>

<script>
import NavBar from "@/components/NavBar/NavBar.vue"
import Popup from "@/components/Popup/Popup.vue"
import { navBack } from "@/utils/utils.js"

export default {
	data() {
		return {
			navBack: navBack,
			show: false,
			query: {},
			page: 0,
			finished: false,
			finished_text: "",
			navBar_class: "",
			user_id: 0,
			userBg: "https://mp-image.scgwlx.com/mp-image/im-default-rmq.jpg",
			works_list: [],
		}
	},
	components: { NavBar, Popup },
	onLoad(options) {
		Object.assign(this.query, options)

		this.user_id = uni.getStorageSync("userInfo").user_id

		//访问记录更新
		if (this.user_id != options.user_id) {
			this.visitorAdd()
		}

		this.onLoadList()
	},
	onShow() {
		// this.works_list.length = 0;
		// this.finished = false;
		// this.page = 0;
		// this.onLoadList();
	},
	onReachBottom() {
		this.onLoadList()
	},
	onPageScroll(e) {
		const scrollTop = e.scrollTop ?? 0

		if (scrollTop > 240) {
			this.navBar_class = "nav-bar__2"
		} else {
			this.navBar_class = ""
		}
	},
	methods: {
		checkResourceType(url) {
			// 检查是否传入了链接
			if (!url || typeof url !== "string") {
				console.error("链接无效，请提供一个有效的字符串链接")
				return "unknown"
			}

			// 常见的图片和视频文件扩展名
			const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "svg", "webp", "tiff", "ico"]
			const videoExtensions = ["mp4", "avi", "mov", "mkv", "webm", "flv", "wmv", "3gp", "mpeg"]

			// 提取文件扩展名，去掉参数和路径后的问号部分
			const extension = url.split(".").pop().toLowerCase().split("?")[0]

			// 判断扩展名是否属于图片或视频
			if (imageExtensions.includes(extension)) {
				return "image"
			} else if (videoExtensions.includes(extension)) {
				return "video"
			} else {
				return "unknown" // 无法识别的文件类型
			}
		},
		visitorAdd() {
			this.$api.friendCircleApi
				.visitorAdd({
					user_id: this.query.user_id,
				})
				.then((res) => {})
		},
		//拍摄 / 从手机相册选择
		release(type) {
			this.show = false

			const maxSize = 5 * 1024 * 1024

			uni.chooseImage({
				sourceType: type,
				count: 9,
				success: (res) => {
					let tempFiles = res.tempFiles
					let validFiles = []

					tempFiles.forEach((file) => {
						// 检查文件大小
						if (file.size > maxSize) {
							uni.showToast({
								title: "文件大小不能超过5MB",
								icon: "none",
							})
						} else {
							validFiles.push(file)
						}
					})

					// 返回合法文件列表
					friendStore.changeReleaseImgs(validFiles)

					uni.navigateTo({
						url: `/pages/friend/release-dynamic/release-dynamic`,
					})
				},
			})
		},
		release() {
			this.show = false
			uni.navigateTo({
				url: `/pages/friend/release-dynamic/release-dynamic`,
			})
		},
		toDetailsMsg(id, isNew) {
			if (isNew) {
				uni.navigateTo({
					url: `/pages/friend/release-dynamic/release-dynamic`,
				})
			} else {
				uni.navigateTo({
					url: `/pages/friend/details-msg/details-msg?trends_id=${id}`,
				})
			}
		},
		//加载更多列表
		onLoadList() {
			//没有更多了
			if (this.finished) {
				uni.showToast({
					title: "没有更多了",
					icon: "error",
				})
				return
			}

			this.$api.friendCircleApi
				.circleIndex({
					page: ++this.page,
					user_id: Number(this.query.user_id),
				})
				.then((res) => {
					const data = res.data ?? []

					const msg = this.page == 1 ? "暂无信息" : "没有更多了"
					this.finished_text = msg

					if (Array.isArray(data)) {
						if (!data.length) {
							this.finished = true
						}

						data.length && this.addNewData(data)
					}
				})
		},
		//前往<访客>
		toVisitor() {
			this.show = false
			uni.navigateTo({
				url: "/pages/friend/visitor/visitor",
			})
		},
		//前往 <发布动态>
		toReleaseDynamic() {
			uni.navigateTo({
				url: "/pages/friend/release-dynamic/release-dynamic",
			})
		},
		// 格式化日期和时间为 'YYYY-MM-DD HH:mm'
		getFormattedDate() {
			const now = new Date()
			const year = now.getFullYear()
			const month = String(now.getMonth() + 1).padStart(2, "0")
			const day = String(now.getDate()).padStart(2, "0")
			const hours = String(now.getHours()).padStart(2, "0")
			const minutes = String(now.getMinutes()).padStart(2, "0")

			return `${year}-${month}-${day} ${hours}:${minutes}`
		},

		// 追加新数据并更新分组结果
		addNewData(newList) {
			const today = new Date().toISOString().split("T")[0] // 获取今天的日期

			// 对新的数据按时间降序排序
			newList.sort((a, b) => new Date(b.date) - new Date(a.date))

			// 检查是否有今天的消息
			// const hasTodayMessage = this.works_list.some((yearGroup) =>
			//   yearGroup.dates.some((dateGroup) =>
			//     dateGroup.items.some((item) => new Date(item.date).toISOString().split('T')[0] === today)
			//   )
			// );
			const hasTodayMessage = newList.some((item) => new Date(item.date).toISOString().split("T")[0] === today)

			if (this.query.user_id == this.user_id) {
				// 如果没有今天的消息，添加一条新的
				if (!hasTodayMessage) {
					const newEntry = {
						date: today,
						img: [],
						content: "分享今天的故事吧...",
						isNew: true,
					}

					const [date, time] = newEntry.date.split(" ")
					const [year, month, day] = date.split("-")
					const monthDay = `${month}-${day}`

					this.addItemToGroup(year, monthDay, newEntry)
				} else if (this.works_list.length) {
					//如果没有今天的消息，则删除这条空消息
					const latestData = this.works_list[0].dates[0].items

					const index = latestData.findIndex((obj) => obj.isNew === true)

					index != -1 && latestData.length && this.works_list[0].dates[0].items.splice(index, 1)
				}
			}

			// 遍历新的数据列表，按日期进行分组
			newList.forEach((item) => {
				const [dates, date] = item.date.split(" ") // 获取日期部分
				const [year, month, day] = dates.split("-") // 获取年份、月份、日期部分
				const monthDay = `${month}-${day}` // 组合月份和日期为 "MM-DD" 格式

				this.addItemToGroup(year, monthDay, item)
			})
		},

		// 将条目添加到分组中
		addItemToGroup(year, date, item) {
			// 将 date 从 "MM-DD" 格式转换为 ["DD", "M月"]
			const [month, day] = date.split("-")
			const formattedDate = [day, `${parseInt(month)}月`]

			// 找到年份分组
			let yearGroup = this.works_list.find((group) => group.year === year)

			if (!yearGroup) {
				// 如果没有找到年份分组，创建一个新的年份分组
				yearGroup = { year, dates: [] }
				this.works_list.push(yearGroup)

				// 按年份降序排序
				this.works_list.sort((a, b) => b.year - a.year)
			}

			// 找到对应日期分组
			// let dateGroup = yearGroup.dates.find((d) => d.date === date);
			let dateGroup = yearGroup.dates.find((d) => d.date[0] === formattedDate[0] && d.date[1] === formattedDate[1])

			if (!dateGroup) {
				// 如果没有找到日期分组，创建一个新的日期分组
				// dateGroup = { date, items: [] };
				dateGroup = { date: formattedDate, items: [] }
				yearGroup.dates.push(dateGroup)

				// 按日期升序排列该年份下的日期分组
				yearGroup.dates.sort((a, b) => new Date(`${year}-${a.date}`) - new Date(`${year}-${b.date}`))
			}

			// 将项目添加到日期分组
			dateGroup.items.push(item)

			// 按时间降序排列该日期下的条目
			dateGroup.items.sort((a, b) => new Date(b.date) - new Date(a.date))
		},
	},
}
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
